package tr.edu.metu.is.mega.server.file;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

/**
 * Downloads files by given request parameters.
 */
public class DownloadServlet extends HttpServlet {

    /** serialVersionUID value. */
    private static final long serialVersionUID = -5272388657179251504L;

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse res) {
        String filepath = req.getParameter("filepath");

        // application/pdf, application/vnd.ms-excel v.s
        String contentType = req.getParameter("contenttype");

        // inline, attachment
        String contentDisposition = req.getParameter("contentdisposition");

        File file = new File(filepath);
        Long fileLength = file.length();

        res.setContentType(contentType);
        res.setHeader("Content-Disposition", String.format("%s; filename=%s", contentDisposition, file.getName()));
        res.setHeader("Content-Length", fileLength.toString());

        BufferedInputStream input = null;
        BufferedOutputStream output = null;

        try {
            input = new BufferedInputStream(new FileInputStream(file));
            output = new BufferedOutputStream(res.getOutputStream());

            IOUtils.copy(input, output);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(input);
            IOUtils.closeQuietly(output);
        }

    }
}
